package eco.lamp;

import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Images.Media;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import eco.lamp.bl.LampItem;
import eco.lamp.bl.LampUpgradeItem;

public class SummaryActivity extends Activity {
	Context mContext;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mContext = this;
		setContentView(R.layout.summary);

		Bundle data = getIntent().getExtras();
		ArrayList<LampUpgradeItem> mItems = data
				.getParcelableArrayList("LampUpgradeItem");

		int oldPower = 0;
		int newPower = 0;
		int oldLifetime = 0;
		int newLifetime = 0;
		int oldOutput = 0;
		int newOutput = 0;

		int ecoEnergy = 0;
		float ecoWaste = 0;

		int totalLifetime = 0;

		int maxLifetime = 0;

		for (LampUpgradeItem item : mItems) {
			LampItem o = item.mLampOld;
			LampItem n = item.mLampNew;
			oldPower += o.getSumPower();
			newPower += n.getSumPower();

			oldLifetime += o.getLife();
			newLifetime += n.getLife();
			totalLifetime += n.getLife() * n.getNumber();
			maxLifetime = Math.max(n.getLife() * n.getNumber(), maxLifetime);
			oldOutput += o.getSumOutput();
			newOutput += n.getSumOutput();

			ecoWaste += ((float) (n.getLife()) / (float) (o.getLife()))
					* n.getNumber();
			ecoEnergy += (o.getPower() * o.getNumber() - n.getPower()
					* n.getNumber())
					* n.getLife();
		}

		oldLifetime = oldLifetime / mItems.size();

		newLifetime = newLifetime / mItems.size();

		double coefOld = (double) oldOutput
				/ (double) Math.max(oldOutput, newOutput);

		TextView txtOutputOld = (TextView) findViewById(R.id.txtOutputOld);
		ImageView imgOutputOld = (ImageView) findViewById(R.id.imgBarOutputOld);
		Bitmap barOld = BitmapFactory.decodeResource(getResources(),
				R.drawable.bar_old);

		int maxTextWidth = 0;
		Paint p = new Paint();
		p.setTextSize(txtOutputOld.getTextSize());
		maxTextWidth = Math.round(p.measureText(String.valueOf(oldOutput)));
		maxTextWidth = Math.max(Math.round(p.measureText(String
				.valueOf(newOutput))), maxTextWidth);
		maxTextWidth = Math.max(Math.round(p.measureText(String
				.valueOf(oldLifetime))), maxTextWidth);
		maxTextWidth = Math.max(Math.round(p.measureText(String
				.valueOf(newLifetime))), maxTextWidth);
		maxTextWidth = Math.max(Math.round(p.measureText(String
				.valueOf(oldPower))), maxTextWidth);
		maxTextWidth = Math.max(Math.round(p.measureText(String
				.valueOf(newPower))), maxTextWidth);

		buildValueBar(maxTextWidth, oldOutput, coefOld, txtOutputOld,
				imgOutputOld, barOld);

		double coefNew = (double) newOutput
				/ (double) Math.max(oldOutput, newOutput);

		TextView txtOutputNew = (TextView) findViewById(R.id.txtOutputNew);
		ImageView imgOutputNew = (ImageView) findViewById(R.id.imgBarOutputNew);
		Bitmap barNew = BitmapFactory.decodeResource(getResources(),
				R.drawable.bar_new);

		buildValueBar(maxTextWidth, newOutput, coefNew, txtOutputNew,
				imgOutputNew, barNew);

		coefOld = (double) oldLifetime
				/ (double) Math.max(oldLifetime, newLifetime);

		TextView txtLiftimeOld = (TextView) findViewById(R.id.txtLifetimeOld);
		ImageView imgLifetimeOld = (ImageView) findViewById(R.id.imgBarLifetimeOld);

		buildValueBar(maxTextWidth, oldLifetime, coefOld, txtLiftimeOld,
				imgLifetimeOld, barOld);

		coefNew = (double) newLifetime
				/ (double) Math.max(oldLifetime, newLifetime);

		TextView txtLifetimeNew = (TextView) findViewById(R.id.txtLifetimeNew);
		ImageView imgLifetimeNew = (ImageView) findViewById(R.id.imgBarLifetimeNew);

		buildValueBar(maxTextWidth, newLifetime, coefNew, txtLifetimeNew,
				imgLifetimeNew, barNew);

		coefOld = (double) oldPower / (double) Math.max(oldPower, newPower);

		TextView txtEnergyOld = (TextView) findViewById(R.id.txtEnergyOld);
		ImageView imgEnergyOld = (ImageView) findViewById(R.id.imgBarEnergyOld);

		buildValueBar(maxTextWidth, oldPower, coefOld, txtEnergyOld,
				imgEnergyOld, barOld);

		coefNew = (double) newPower / (double) Math.max(oldPower, newPower);

		TextView txtEnergyNew = (TextView) findViewById(R.id.txtEnergyNew);
		ImageView imgEnergyNew = (ImageView) findViewById(R.id.imgBarEnergyNew);

		buildValueBar(maxTextWidth, newPower, coefNew, txtEnergyNew,
				imgEnergyNew, barNew);

		TextView txtSummaryInfoStart = (TextView) findViewById(R.id.txtSummaryInfoStart);
		String startTemplate = getResources().getString(
				R.string.strSummaryTemplateStart);
		String start = MessageFormat.format(startTemplate, maxLifetime);
		txtSummaryInfoStart.setText(start);

		float kw = ecoEnergy / 1000;
		float c = kw * 0.4065f;
		float g = kw * 2.93f;
		float o = kw * 3.41f;
		float co2 = kw * 1.5f;

		String volume = getString(R.string.strCubicMeter);
		String weight = getString(R.string.strKiloGramm);
		String liquid = getString(R.string.strLiter);

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);

		int units = Integer.valueOf(preferences.getString("unitSystem", "1"));

		if (units == 2) {
			c /= 0.4536f;
			g /= 0.7646f;
			o /= 119.24f;
			co2 /= 0.7646f;
			volume = getString(R.string.strCubicYard);
			weight = getString(R.string.strPounds);
			liquid = getString(R.string.strBarrel);
		}

		TextView txtSummaryInfoEnergy = (TextView) findViewById(R.id.txtSummaryInfoEnergy);
		String energyTemplate = getResources().getString(
				R.string.strSummaryTemplateEnergy);
		String energy = MessageFormat.format(energyTemplate, kw, c, weight, g,
				volume, o, liquid);
		txtSummaryInfoEnergy.setText(energy);

		TextView txtSummaryInfoCO = (TextView) findViewById(R.id.txtSummaryInfoCO);
		String coTemplate = getResources().getString(
				R.string.strSummaryTemplateCO);
		String co = MessageFormat.format(coTemplate, co2, volume);
		txtSummaryInfoCO.setText(co);

		TextView txtSummaryInfoWaste = (TextView) findViewById(R.id.txtSummaryInfoWaste);
		String wasteTemplate = getResources().getString(
				R.string.strSummaryTemplateWaste);
		String waste = MessageFormat.format(wasteTemplate, ecoWaste);
		txtSummaryInfoWaste.setText(waste);

		TextView txtSummaryInfoCost = (TextView) findViewById(R.id.txtSummaryInfoCost);
		String costTemplate = getResources().getString(
				R.string.strSummaryTemplateCost);

		Float price = Float.valueOf(preferences.getInt("electricityPrice",
				Integer.valueOf(getString(R.string.intElectricityPrice))));
		Float cost = kw * price / 100;
		String costStr = MessageFormat.format(costTemplate, cost, price);
		txtSummaryInfoCost.setText(costStr);

		final Bitmap userbar = generateBanner(kw, kw * 1.5f, ecoWaste);

		ImageButton btnShare = (ImageButton) findViewById(R.id.btnShare);
		btnShare.setImageBitmap(userbar);
		btnShare.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				Uri uri = storeUserbar(userbar);
				Date now = new Date(System.currentTimeMillis());
				String date = DateFormat.getDateFormat(mContext).format(now)
						+ " " + DateFormat.getTimeFormat(mContext).format(now);
				Intent i = new Intent(Intent.ACTION_SEND);
				i.putExtra(Intent.EXTRA_SUBJECT, "ecoLamp userbar");
				i.putExtra(Intent.EXTRA_STREAM, uri);
				i.putExtra(Intent.EXTRA_TEXT,
						"Hi!\nThis ecoLamp userbar generated " + date);
				i.setType("image/jpeg");
				startActivity(Intent.createChooser(i, getResources().getText(
						R.string.lbSend)));

			}
		});

		Button btnBack = (Button) findViewById(R.id.btnSummaryBack);
		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		Button btnExit = (Button) findViewById(R.id.btnSummaryExit);
		btnExit.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				setResult(RESULT_OK);
				finish();
			}
		});
	}

	private void buildValueBar(int txtSize, int value, double coef,
			TextView txtOutputOld, ImageView img, Bitmap bar) {

		txtOutputOld.setText(String.valueOf(value));
		int width = getWindowManager().getDefaultDisplay().getWidth();
		width -= (txtSize + txtOutputOld.getPaddingRight()
				+ img.getPaddingLeft() + img.getPaddingRight());
		Paint p = new Paint();
		p.setTextSize(txtOutputOld.getTextSize());
		int txtSizeCurrent = (int) p.measureText(String.valueOf(value));
		txtOutputOld.setPadding(txtSize - txtSizeCurrent, txtOutputOld
				.getPaddingTop(), txtOutputOld.getPaddingRight(), txtOutputOld
				.getPaddingBottom());
		double dw = bar.getWidth() / 2;
		int h = bar.getHeight();
		Bitmap result = Bitmap.createBitmap(width, h, Config.RGB_565);
		int cnt = (int) Math.round(((((double) width) / dw) * coef)
				- Math.round(1 * coef));
		Canvas canvas = new Canvas(result);

		canvas.drawColor(getResources().getColor(R.color.bg2Color));
		
		int x = 0;
		for (int i = 0; i < cnt; i++) {
			canvas.drawBitmap(bar, x, 0, p);
			x += dw;
		}
		img.setImageBitmap(result);
	}

	private Uri storeUserbar(Bitmap bitmap) {
		ContentValues values = new ContentValues(3);
		values.put(Media.DISPLAY_NAME, "ecolamp_userbar.jpg");
		values.put(Media.TITLE, "ecolamp_userbar.jpg");
		values.put(Media.DESCRIPTION, "ecolamp userbar");
		values.put(Media.MIME_TYPE, "image/jpeg");
		Uri saveUri = Media.EXTERNAL_CONTENT_URI;

		Cursor cur = managedQuery(saveUri, new String[] { MediaColumns._ID },
				MessageFormat.format("{0} = \"{1}\"", MediaColumns.TITLE,
						"ecolamp_userbar.jpg"), null, null);
		Uri uri = null;
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			long id = cur.getLong(cur.getColumnIndex(MediaColumns._ID));
			uri = Uri.withAppendedPath(saveUri, String.valueOf(id));

		} else {
			uri = getContentResolver().insert(saveUri, values);
		}
		try {
			OutputStream outStream = getContentResolver().openOutputStream(uri);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
			outStream.close();
		} catch (Exception e) {
			Log.e("ecoLamp", "exception while writing image", e);
		}
		return uri;
	}

	private Bitmap generateBanner(float ecoPower, float ecoCO2, float ecoWaste) {
		Bitmap result = Bitmap.createBitmap(350, 19, Config.RGB_565);
		Drawable userbar = getResources().getDrawable(R.drawable.userbar);
		Canvas canvas = new Canvas(result);
		userbar.setBounds(0, 0, 350, 19);
		userbar.draw(canvas);
		Paint paint = new Paint();
		paint.setTextSize(14);
		paint.setColor(Color.WHITE);
		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"fonts/visitor2.ttf");
		paint.setTypeface(typeface);
		canvas.drawText(MessageFormat.format("{0, number, #.##}", ecoPower),
				105, 17, paint);
		canvas.drawText(MessageFormat.format("{0, number, #.##}", ecoCO2), 190,
				17, paint);
		canvas.drawText(MessageFormat.format("{0, number, #.##}", ecoWaste),
				273, 17, paint);
		return result;
	}
}
